# Bar System - 创建Windows任务计划
# 等同于Linux的crontab，用于定期检查和启动服务

# 需要管理员权限运行
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")) {
    Write-Host "请以管理员身份运行此脚本!" -ForegroundColor Red
    Write-Host "右键点击PowerShell，选择'以管理员身份运行'" -ForegroundColor Yellow
    pause
    exit
}

$BaseDir = "D:\test\bar"
$TaskName = "BarSystemAutoStart"
$CheckTaskName = "BarSystemHealthCheck"

Write-Host "=== Bar System 任务计划设置 ===" -ForegroundColor Cyan

# 删除已存在的任务
Write-Host "`n清理旧任务..." -ForegroundColor Yellow
try {
    Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false -ErrorAction SilentlyContinue
    Unregister-ScheduledTask -TaskName $CheckTaskName -Confirm:$false -ErrorAction SilentlyContinue
    Write-Host "旧任务已清理" -ForegroundColor Green
} catch {
    # 忽略错误
}

# 1. 创建系统启动时自动启动服务的任务
Write-Host "`n创建【系统启动时自动启动】任务..." -ForegroundColor Cyan

$StartAction = New-ScheduledTaskAction -Execute "powershell.exe" `
    -Argument "-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$BaseDir\start-services.ps1`""

$StartTrigger = New-ScheduledTaskTrigger -AtStartup

$StartSettings = New-ScheduledTaskSettingsSet `
    -AllowStartIfOnBatteries `
    -DontStopIfGoingOnBatteries `
    -StartWhenAvailable `
    -ExecutionTimeLimit (New-TimeSpan -Hours 0) `
    -RestartCount 3 `
    -RestartInterval (New-TimeSpan -Minutes 1)

Register-ScheduledTask -TaskName $TaskName `
    -Action $StartAction `
    -Trigger $StartTrigger `
    -Settings $StartSettings `
    -Description "Bar System 自动启动服务（系统启动时）" `
    -RunLevel Highest | Out-Null

Write-Host "  ✓ 系统启动时自动启动任务已创建" -ForegroundColor Green

# 2. 创建每分钟健康检查任务（类似crontab */1 * * * *）
Write-Host "`n创建【每分钟健康检查】任务..." -ForegroundColor Cyan

# 创建健康检查脚本
$HealthCheckScript = @"
# 健康检查和自动恢复脚本
`$BaseDir = "$BaseDir"

function Check-ServiceRunning {
    param([int]`$Port)
    `$connection = Test-NetConnection -ComputerName localhost -Port `$Port -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
    return `$connection.TcpTestSucceeded
}

# 检查后端服务
if (-not (Check-ServiceRunning -Port 38521)) {
    Write-Output "[`$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] 后端服务未运行，正在启动..." | Out-File -Append "`$BaseDir\health-check.log"
    Start-Process powershell -ArgumentList "-NoProfile", "-WindowStyle Hidden", "-Command `"cd '`$BaseDir\backend'; node server.js | Out-File -Append logs\service.log`"" -PassThru | Out-Null
}

# 检查Web前端服务
if (-not (Check-ServiceRunning -Port 35280)) {
    Write-Output "[`$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] Web前端服务未运行，正在启动..." | Out-File -Append "`$BaseDir\health-check.log"
    Start-Process powershell -ArgumentList "-NoProfile", "-WindowStyle Hidden", "-Command `"cd '`$BaseDir\web'; npm run dev -- --host | Out-File -Append logs\service.log`"" -PassThru | Out-Null
}
"@

Set-Content -Path "$BaseDir\health-check.ps1" -Value $HealthCheckScript -Encoding UTF8

$CheckAction = New-ScheduledTaskAction -Execute "powershell.exe" `
    -Argument "-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$BaseDir\health-check.ps1`""

# 创建每分钟触发器
$CheckTrigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 1) -RepetitionDuration ([TimeSpan]::MaxValue)

$CheckSettings = New-ScheduledTaskSettingsSet `
    -AllowStartIfOnBatteries `
    -DontStopIfGoingOnBatteries `
    -StartWhenAvailable `
    -ExecutionTimeLimit (New-TimeSpan -Seconds 30)

Register-ScheduledTask -TaskName $CheckTaskName `
    -Action $CheckAction `
    -Trigger $CheckTrigger `
    -Settings $CheckSettings `
    -Description "Bar System 健康检查（每分钟）" `
    -RunLevel Highest | Out-Null

Write-Host "  ✓ 每分钟健康检查任务已创建" -ForegroundColor Green

# 显示任务信息
Write-Host "`n=== 任务计划创建完成 ===" -ForegroundColor Green
Write-Host "`n已创建的任务:" -ForegroundColor Cyan
Write-Host "  1. $TaskName" -ForegroundColor White
Write-Host "     - 系统启动时自动启动服务" -ForegroundColor Gray
Write-Host "`n  2. $CheckTaskName" -ForegroundColor White
Write-Host "     - 每分钟检查服务健康状态" -ForegroundColor Gray
Write-Host "     - 服务停止时自动恢复" -ForegroundColor Gray

Write-Host "`n管理任务:" -ForegroundColor Cyan
Write-Host "  查看任务: taskschd.msc" -ForegroundColor Gray
Write-Host "  删除任务: Unregister-ScheduledTask -TaskName `"$TaskName`"" -ForegroundColor Gray

Write-Host "`n日志文件:" -ForegroundColor Cyan
Write-Host "  健康检查日志: $BaseDir\health-check.log" -ForegroundColor Gray
Write-Host "  后端日志: $BaseDir\backend\logs\service.log" -ForegroundColor Gray
Write-Host "  Web日志: $BaseDir\web\logs\service.log" -ForegroundColor Gray

Write-Host "`n提示: 你现在可以关闭此窗口，服务将自动管理" -ForegroundColor Yellow
pause
"@

Set-Content -Path "$BaseDir\setup-task-scheduler.ps1" -Value $script:MyInvocation.MyCommand.ScriptContents -Encoding UTF8
